package com.mutual.commom.service;

import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;


public class RedisService {

	@Resource
	private StringRedisTemplate stringRedisTemplate;
	
	private static final Logger logger = LoggerFactory.getLogger(RedisService.class);
	
	/**
	 * 添加数据
	 * @param key
	 * @param value
	 * @param time 单位是秒
	 */
	public void saveRedisValueTime(String key,String value,long time){
		stringRedisTemplate.opsForValue().set(key, value);
		stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);//多少秒钟自动失效
		logger.info("保存key值{}，value值{}，时间为{}秒",key,value,time);
	}
	
	/**
	 * 删除key
	 * @param key
	 */
	public void deleteRedisByKey(String key){
		String value=stringRedisTemplate.boundValueOps(key).get();
		if(StringUtils.isEmpty(value)){
			logger.info("不存在key值，终止删除操作");
			return;
		}
		logger.info("存在有key值{}，已删除",key);
		stringRedisTemplate.delete(key);
	}
	
	/**
	 * 查询值
	 * @param key
	 * @return
	 */
	public String getValueByRedisKey(String key){
		return stringRedisTemplate.boundValueOps(key).get();
	}
}
